package design.graduation.novelsystem.shiro;

import design.graduation.novelsystem.constant.Constant;
import design.graduation.novelsystem.model.domian.Admin;
import design.graduation.novelsystem.model.dto.ActiveAdmin;
import design.graduation.novelsystem.service.AdminService;
import design.graduation.novelsystem.service.MenuService;
import design.graduation.novelsystem.service.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author: 洪少尉
 * @Date: 2020/4/9 10:04
 * @Description: shiro用户认证和授权配置
 */

public class UserRealm extends AuthorizingRealm {
	@Autowired
	private AdminService adminService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private MenuService menuService;

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		//1.判断用户名
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		Admin admin = adminService.findByUserName(token.getUsername());
		//用户存在
		if(admin != null){
			ActiveAdmin activeAdmin=new ActiveAdmin();
			//设置管理员信息
			activeAdmin.setAdmin(admin);
			//根据管理员id查询拥有的角色名称
			List<String> roles=this.roleService.queryRoleNamesByAdminId(admin.getId());
			//根据管理员ID去查询权限编码的集合
			List<String> permissions=this.menuService.queryPermissionCodesByAdminId(admin.getId());
			activeAdmin.setRoles(roles);
			activeAdmin.setPermissions(permissions);
			return new SimpleAuthenticationInfo(activeAdmin,admin.getPassword(), ByteSource.Util.bytes(admin.getSalt()),getName());
		}
		return null;
	}

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
		ActiveAdmin activeAdmin= (ActiveAdmin) principalCollection.getPrimaryPrincipal();
		List<String> permissions = activeAdmin.getPermissions();
		List<String> roles = activeAdmin.getRoles();
		Admin admin = activeAdmin.getAdmin();
		//或为超级管理员
		if(admin.getType().equals(Constant.USER_TYPE_SUPER)){
			//授予所有权限
			info.addStringPermission("*:*");
		}else{
			if( null!= roles && roles.size()>0){
				info.addRoles(roles);
			}
			if(null !=permissions && permissions.size()>0){
				info.addStringPermissions(permissions);
			}
		}
		return info;
	}

	@Override
	public String getName() {
		return this.getClass().getSimpleName();
	}
}
